package com.rxmvp.rxjavademo.RxRetrofit;

import com.rxmvp.rxjavademo.RxRetrofit.exception.CodeException;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/1/12.
 */

public class BaseTransformer<T> implements Observable.Transformer<T, T> {

    @Override
    public Observable<T> call(Observable<T> baseResponseObservable) {
        return baseResponseObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .timeout(5, TimeUnit.SECONDS)  //超时为5s
                .retry(5)  //重连5次
                .flatMap(new Func1<T, Observable<T>>() {
                    @Override
                    public Observable<T> call(T tBaseResponse) {
                        return flatResponse(tBaseResponse);
//                        return Observable.just(tBaseResponse);
                    }
                });
    }

    /**
     * 对网络接口返回的Response进行分割操作
     *
     * @param response BaseResponse
     * @return Observable
     */
    private Observable<T> flatResponse(final T response) {
        return Observable.create(new Observable.OnSubscribe<T>() {
            @Override
            public void call(Subscriber<? super T> subscriber) {
                if (response == null) {
                    //数据为空，抛出异常
                    subscriber.onError(new CodeException(CodeException.DATA_NULL_ERROR));
                }
                subscriber.onCompleted();
            }
        });
    }
}
